<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/25
 * Time: 11:09
 */

namespace app\home\controller;

use app\home\model\Block;
use app\home\model\VersionsBlock;
use think\Db;
use app\home\model\Project;
use app\common\controller\Backend;

/**
 * @title 版本管理
 * @description 接口说明
 * @group 后台管理
 */
class Versions extends Backend
{
    protected $hsModel = 'Versions';

    /**
     * @title 版本需求/BUG 页
     * @description 接口说明
     * @author jyh
     * @url /versions/getContent/:action
     * @method POST
     * @param name:id type:int require:1 default:null other: desc:版本id
     * @param name:action type:string require:1 default:need other: desc:need/bug
     * @return id:需求编号
     * @return project_id:项目id
     * @return status:需求状态 0=筹备中 1=待开发 2=开发中 3=待测试 4=测试中 5=待上线 6=已上线
     * @return product_id:关联产品
     * @return type:需求类型
     * @return describe:需求描述
     * @return source:需求来源
     * @return priority:优先级
     * @return front_user:前端开发
     * @return after_user:后端开发
     * @return creator:创建人
     * @return assigner:指派给某人
     * @return ctime:创建时间
     * @return etime:截止时间
     */
    public function getContent($action = 'need')
    {
        if ( $this->request->isPost() ) {
            $this->hsModel = $action == 'need' ? 'projectNeed' : 'projectBug';
            $param = $this->request->param();
            $page = (int)input('page', 1);
            $limit = (int)input('limit', 10);
            if ( !isset($param['versions_id']) ){
                return json(['code' => 1,'msg' => '参数错误']);
            }
            $map = [];
            $map['versions_id'] = $param['versions_id'];
            if ( isset($param['id']) ) $map['id'] = $param['id'];
            $data = Db::name($this->hsModel)
                ->where('deleted',null)
                ->where($map);
                if ($action == 'need') $data = $data->where('task_allot=0 or task_allot=4');
            $data = $data->order('ctime','desc')
                ->paginate([
                    'page' => $page,
                    'list_rows' => $limit,
                ], false)
            ->toArray();
            $projectName = Db::name('project')->column('name','id');
            $block = Db::name('block')->where('deleted',null)->column('name','id');
            $deploy = Db::name('deploy')->where('deleted',null)->column('name','id');
            $user = Db::name('user')->where('deleted',0)->column('name','id');
            if ($action == 'need') {
                if (USER_DEPT == 0) {
                    $prefix = 'front_';
                } else if (USER_DEPT == 1) {
                    $prefix = 'after_';
                }
                if ($action == 'need') {
                    foreach ($data['data'] as $key => $value) {
                        $data['data'][$key]['status'] = \app\home\model\ProjectNeed::$statusCode[$value['status']];
                        $data['data'][$key]['project_id'] = $projectName[$value['project_id']];
                        $data['data'][$key]['product_id'] = $projectName[$value['product_id']];
                        $data['data'][$key]['block_id'] = $block[$value['block_id']];
                        $data['data'][$key]['type'] = $deploy[$value['type']];
                        $data['data'][$key]['source'] = $deploy[$value['source']];
                        $data['data'][$key]['priority'] = $deploy[$value['priority']];
                        $data['data'][$key]['creator'] = $user[$value['creator']];
                        $data['data'][$key]['front_user'] = $value['front_user'] ? $user[$value['front_user']] : '';
                        $data['data'][$key]['after_user'] = $value['after_user'] ? $user[$value['after_user']] : '';
                        $data['data'][$key]['ptime'] = $value['ptime'] ? date('Y-m-d',$value['ptime']) : '';
                        $data['data'][$key]['etime'] = $value['etime'] ? date('Y-m-d',$value['etime']) : '';
                    }
                    if (isset($prefix)) {
                        foreach ($data['data'] as $key => $value) {
                            $data['data'][$key]['isshow'] = $value[$prefix.'predict'] > 0 ? false : true;
                            $data['data'][$key]['isself'] = $value[$prefix.'user'] == USER_NAME ? true : false;
                            $data['data'][$key]['isfinish'] = $value[$prefix.'plan'] == 100 ? false : true;
                            $data['data'][$key]['isup'] = $value['isup'] == 1 ? false : true;
                        }
                    }
                } else {
                    foreach ($data['data'] as $key => $value) {
                        $data['data'][$key]['etime'] = $data[$key]['etime'] ? date('Y-m-d', $value['etime']) : '' ;
                        $data['data'][$key]['isself'] = $value['assigner'] == USER_NAME ? true : false;
                    }
                }
            }
            if ( empty($data['data']) ) {
                return json(['code' => 0,'msg' => '暂无数据']);
            }

            return json(['code' => 0, 'msg' => '成功','data' => $data]);
        }
        return json(['code' => 0, 'msg' => '请求有误，请重新确认请求！']);
    }

    /**
     * @title 查询版本下模块
     * @description 接口说明
     * @author 开发者 [jyh]
     * @url /versions/getBlock/:id
     * @method POST
     * @param name:id type:int require:1 default: other: desc:版本id
     */
    public function getBlock($id)
    {
        if ( $this->request->isPost() ) {
            $vid = $this->request->post('vid');
            // 获取 模块总数
            $model = $this->model();
            if (isset($vid)) {
                $vid = $model->where('product_id',$id)->order('ctime','desc')->value('id');
            } else {
                $vid = $id;
            }
            $block = $model->with('block')->where('id',$vid)->field('id,name')->select();
            return json(['code' => 0, 'msg' => '模块', 'data' => $block]);
        }
    }
    /**
     * @title 版本管理增加产品
     * @description 接口说明
     * @author 开发者 [jyh]
     * @url /versions/addProduct
     * @method POST
     * @param name:product_name type:string require:1 default: other: desc:产品名称
     * @param name:versions_name type:string require:1 default: other: desc:版本名称
     * @param name:block type:array require:1 default: other: desc:模块
     */
    public function addProduct()
    {
        if ( $this->request->isPost() ) {
            $params = $this->request->post();
            // 启动事务
            Db::startTrans();
            try {
                $map = [];
                // 判断产品是否存在
                if (!isset($params['product_id'])) {
                    $project = new project();
                    $map['name'] = $params['product_name'];
                    $map['status'] = 5;
                    // 检查该产品名是否存在
                    $result = $project->where($map)->find();

                    if ($result) {
                        Db::rollback();
                        return json(['code' => 1, 'msg' => '项目已存在']);
                    }
                    $map['creator'] = USER_ID;
                    $map['ctime'] = time();

                    $params['product_id'] = $project->insertGetId($map);
                    if (!$params['product_id']) {
                        Db::rollback();
                        return json(['code' => 1, 'msg' => '产品增加失败']);
                    }
                }
                $map = [];
                $versions = $this->model();
                // 判断版本id和name同时存在则修改
                if (isset($params['versions_id']) && isset($params['versions_name'])) {
                    $versions->save(['name' => $params['versions_name']], ['id' => $params['versions_id']]);
                } else {
                    $map['product_id'] = $params['product_id'];
                    $params['status'] = isset($params['status']) ? $params['status'] : 1;
                    // 判断版本id是否存在
                    if (!isset($params['versions_id'])) {
                        if ($params['status'] == 1) {
                            $versions->save(['status' => 0, 'history' => 0], $map);
                        }
                        // 不存在则添加一个版本
                        $map['name'] = $params['versions_name'];
                        // 检查该版本name是否存在
                        $result = $versions->where($map)->find();
                        if ($result) {
                            Db::rollback();
                            return json(['code' => 1, 'msg' => '产品版本已存在']);
                        }
                        $map['ctime'] = time();
                        $map['creator'] = USER_ID;
                        $map['status'] = $params['status'] == 5 ? 1 : $params['status'];
                        $params['versions_id'] = $versions->insertGetId($map);
                    } else {
                        if ($params['status'] == 1) {
                            $versions->save(['status' => 0, 'history' => 0], $map);
                        }
                        // 存在则修改版本id和产品id数据状态
                        $map['id'] = $params['versions_id'];
                        $versions->save(['status' => $params['status'], 'history' => 1], $map);
                    }
                }

                $blockId = [];
                if (isset($params['block'])) {
                    if (isset($params['block_id'])) {
                        $block_id = $params['block_id'];
                        unset($params['block_id']);
                        foreach ($params['block'] as $key => $value) {
                            if ($block_id[$key] != '') {
                                $blockId[] = $block_id[$key];
                                Db::name('block')->where('id', $block_id[$key])->update(['name' => $value]);
                            } else {
                                $result = Db::name('block')->where('name', $value)->find();
                                if (isset($result)) {
                                    $blockId[] = $result['id'];
                                } else {
                                    $blockId[] = Db::name('block')->insertGetId(['name' => $value]);
                                }
                            }
                        }
                    } else {
                        foreach ($params['block'] as $key => $value) {
                            $result = Db::name('block')->where('name', $value)->find();
                            if (isset($result)) {
                                $blockId[] = $result['id'];
                            } else {
                                $blockId[] = Db::name('block')->insertGetId(['name' => $value]);
                            }
                        }
                    }
                    $versionsBlock = new VersionsBlock();
                    $arr = [[(int)$params['versions_id']], $blockId];
                    $groupData = $this->get_group($arr, ['versions_id', 'block_id']);
                    $versionsBlock->where('versions_id', $params['versions_id'])->delete();
                    $versionsBlock->allowField(true)->saveAll($groupData[0]);
                }
                // 提交事务
                Db::commit();
                return json(['code' => 0, 'msg' => 'ok']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * @title 删除产品
     * @author 开发者 [jyh]
     * @url /versions/del/:id
     * @method POST
     * @param name:id type:int require:1 default: other: desc:版本id
     */
    public function del($ids = "")
    {
        // 模型事件 在插入前执行图片插入
        $this->model()::event('after_delete', function ($result) {
            $id = $result->id;
            $needModel = new \app\home\model\ProjectNeed();
            $bugModel = new \app\home\model\ProjectBug();
            $needModel->where('versions_id',$id)->update(['deleted' => time()]);
            $bugModel->where('versions_id',$id)->update(['deleted' => time()]);
        });
        return parent::del($ids); // TODO: Change the autogenerated stub
    }

    /**
     * @title 删除模块
     * @author 开发者 [jyh]
     * @url /versions/delBlock/:id
     * @method POST
     * @param name:id type:int require:1 default: other: desc:版本id
     */
    public function delBlock($ids = "")
    {
        // 启动事务
        Db::startTrans();
        try {
            Db::name('block')->where('id',$ids)->update(['deleted' => time()]);
            Db::name('versionsBlock')->where('block_id',$ids)->update(['deleted' => time()]);
            Db::name('projectNeed')->where('block_id',$ids)->update(['deleted' => time()]);
            Db::name('projectBug')->where('block_id',$ids)->update(['deleted' => time()]);
            Db::commit();
            return json(['code' => 0, 'msg' => 'ok']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @title 修改产品
     * @description 接口说明
     * @author 开发者 [jyh]
     * @url /versions/edit/:id
     * @method POST
     * @param name:name type:int require:1 default: other: desc:产品名
     */
    public function edit($ids = null)
    {
        return parent::edit($ids); // TODO: Change the autogenerated stub
    }

    //禁用 || 启用
    public function enable(){
        $params = input();
        $id = !empty($params['id']) ? $params['id'] : '';
        $product_id = !empty($params['product_id']) ? $params['product_id'] : '';
        $status = !empty($params['status']) ? $params['status'] : 0;

        if(!$id || !$product_id){
            return json(['msg'=>'参数错误','code'=>1]);
        }

        $map = ['id' => $id];

        Db::startTrans();
        try {
            $model = $this->model();
            $save = $model->where($map)->update(['status' => $status]);

            if($save !== false) {
                $ctime = $model->where('id',$id)->value('ctime');
                $model->where('product_id', $product_id)->where('ctime','>=',$ctime)->update(['history' => 1]);
                $model->where('product_id', $product_id)->where('ctime','<',$ctime)->update(['history' => 0]);
                $res = $model->where('product_id', $product_id)->where('id','<>', $id)->update(['status' => 0]);
            } else {
                Db::rollback();
                return json(['msg'=>'操作失败','code'=>1]);
            }

            if($res !== false){
                // 提交事务
                Db::commit();
                return json(['msg'=>'操作成功','code'=>0]);
            }else{
                Db::rollback();
                return json(['msg'=>'操作失败','code'=>1]);
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }
}